package com.dashan.backend.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpRequestSender {
    
   private String content = "";
   private String rawContent = "";
    private String urlString;
    private String rawRes = "";

    public HttpRequestSender(String address, String serviceUrl) {
        this.urlString = "http://" + address + serviceUrl;
    }
    public String sendPost() throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setAllowUserInteraction(true);
        conn.setConnectTimeout(5000);
        
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        
        out.writeBytes(content);
        out.flush();
        out.close();
        
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        String res = "";
        while ((line = in.readLine()) != null) {
            rawRes += line + "\n";
            res += encodeHtml(line) +"<br>";
        }
        return res;
    }
    
    public void addParameter(String name, String value) {
        try {
            if (content.compareTo("") == 0) {
                content = name + "=" + URLEncoder.encode(value, "UTF-8");
                rawContent = name + "=" + value;
            } else {
                    content += "&" + name + "=" + URLEncoder.encode(value, "UTF-8");
                    rawContent += "&" + name + "=" + value;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    
    /** return StringBuilder and/or make Writer param and write to stream directly. **/
    public static String encodeHtml(String s)
    {
        StringBuilder buf = new StringBuilder(s.length());
        for ( int i = 0; i < s.length(); i++ )
        {
            char c = s.charAt( i );
            if ( c>='a' && c<='z' || c>='A' && c<='Z' || c>='0' && c<='9' )
            {
                buf.append( c );
            }
            else
            {
                buf.append("&#").append((int)c).append(";");
            }
        }
        return buf.toString();
    }
    
    public String getRawRes() {
        return rawRes;
    }
    
    public String getParameters() {
        return rawContent;
    }
}
